﻿using System.IO;
using System.Linq;
using LocalOverride.Fiddler.UrlMapping;

namespace LocalOverride.Fiddler.Store
{
    public class SpecialCaseMappingsProvider : ISpecialCaseMappingsProvider
    {
        private readonly MappingEntry mappingEntry;

        public SpecialCaseMappingsProvider(MappingEntry mappingEntry)
        {
            this.mappingEntry = mappingEntry;
        }

        public MappingResult GetMappingResult(string requestUrl)
        {
            foreach (var specialCaseMapping in mappingEntry.SpecialCaseMappings)
            {
                if(requestUrl == specialCaseMapping.Url)
                {
                    return new MappingResult(specialCaseMapping.LocalPath, false);
                }
            }
            return MappingResult.NoMapping;
        }

        public string MakeSpecialCase(string requestUrl, string localPath)
        {
            var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(localPath);
            var filePath = Path.GetDirectoryName(localPath);
            var fileExtension = Path.GetExtension(localPath);

            var localPathsUsed = mappingEntry.SpecialCaseMappings.Select(x => x.LocalPath).ToList();

            string newLocalFile;

            var i = 0;
            do
            {
                i++;
                var newFileName = fileNameWithoutExtension + "_" + i + fileExtension;
                newLocalFile = Path.Combine(filePath, newFileName);
            } while (localPathsUsed.Contains(newLocalFile));

            mappingEntry.SpecialCaseMappings.Add(new SpecialCaseMapping{Url = requestUrl, LocalPath = newLocalFile});
            return newLocalFile;
        }
    }
}